package com.jfinal.weixin.sdk.api;

import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.RetryUtils;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Created by mason on 17-7-3.
 * refresh accessToken
 */
public interface AccessTokenHelper {

    /**
     * 无条件强制更新 access token 值
     * @param ac ApiConfig
     * @return AccessToken
     */
    AccessToken refresh(ApiConfig ac);

    class DefaultAccessTokenHelper implements AccessTokenHelper {

        private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

        @Override
        public AccessToken refresh(ApiConfig ac) {
            String appId = ac.getAppId();
            String appSecret = ac.getAppSecret();
            final Map<String, String> queryParas = ParaMap.create("appid", appId).put("secret", appSecret).getData();

            // 最多三次请求
            AccessToken result = RetryUtils.retryOnException(3, new Callable<AccessToken>() {

                @Override
                public AccessToken call() throws Exception {
                    String json = HttpUtils.get(url, queryParas);
                    return new AccessToken(json);
                }
            });

            return result;
        }
    }
}
